package com.spring.quickstart.controller.demo;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.spring.quickstart.common.validator.groups.Add;
import com.spring.quickstart.entity.User;
import com.spring.quickstart.service.IDemoService;

@Controller
public class ValidatorAction {

	@Autowired
	private IDemoService demoService;

	//http://127.0.0.1:8080/demo/addUser.json?userName=xiongxin&password=123456
	@RequestMapping(value = "/demo/addUser", method = RequestMethod.GET, produces = { "application/json;charset=UTF-8" })
	@ResponseBody
	public Map<String, Object> addUser(HttpServletRequest request, @Validated({ Add.class }) User user, BindingResult bindingResult) {
		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("errNo", -1);//默认成功
		resultMap.put("errMsg", "参数校验成功");//默认成功

		//Web端验证
		/*if (bindingResult.hasErrors()) {
			StringBuilder sBuilder = new StringBuilder();
			for (FieldError fieldError : bindingResult.getFieldErrors()) {
				sBuilder.append(fieldError.getField() + ":" + fieldError.getDefaultMessage() + "|");
			}
			resultMap.put("errNo", 0);//验证失败
			resultMap.put("errMsg", "参数校验失败！" + sBuilder.toString());
		}*/

		//服务层验证
		Map<String, Object> retMap = demoService.addUser(user);
		resultMap.putAll(retMap);

		return resultMap;
	}
}
